package com.itheima.filter;/*
 *      .--,       .--,
 *     ( (  \.---./  ) )
 *     '.__/o   o\__.'
 *        {=  ^  =}
 *         >  -  <
 *        /       \
 *       //       \\
 *      //|   .   |\\
 *      "'\       /'"_.-~^`'-.
 *         \  _  /--'         `
 *       ___)( )(___
 *      (((__) (__)))    高山仰止,景行行止.虽不能至,心向往之。
 *
 * @author JiaoDaoNiu
 * @create 2022-09-23-10:39
 */

import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Configuration
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取登陆用户
        Long empId = (Long) request.getSession().getAttribute("employee");
        if(empId!=null){
            //后台用户已登录,放心。
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("user"));
            BaseContext.setCurrentId(empId);

            return true;
        }


        //获取登陆用户
        Long userId = (Long) request.getSession().getAttribute("user");
        if(userId!=null){
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("user"));
            //后台用户已登录,放心。
            BaseContext.setCurrentId(userId);
            return true;
        }

        //没有登录 不放行
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {


        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
